package com.ftg.learn.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes 文件字节数组
     * @param objectName 对象名称
     * @return 文件访问路径
     * @throws OSSException OSS异常
     * @throws ClientException 客户端异常
     */
    public String upload(byte[] bytes, String objectName) throws OSSException, ClientException {
        // 参数校验
        if (bytes == null || bytes.length == 0) {
            throw new IllegalArgumentException("文件内容不能为空");
        }
        if (!StringUtils.hasText(objectName)) {
            throw new IllegalArgumentException("对象名称不能为空");
        }
        if (!StringUtils.hasText(endpoint)) {
            throw new IllegalArgumentException("endpoint不能为空");
        }
        if (!StringUtils.hasText(accessKeyId)) {
            throw new IllegalArgumentException("accessKeyId不能为空");
        }
        if (!StringUtils.hasText(accessKeySecret)) {
            throw new IllegalArgumentException("accessKeySecret不能为空");
        }
        if (!StringUtils.hasText(bucketName)) {
            throw new IllegalArgumentException("bucketName不能为空");
        }

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
            
            // 文件访问路径规则 https://BucketName.Endpoint/ObjectName
            String url = String.format("https://%s.%s/%s", bucketName, endpoint, objectName);
            log.info("文件上传成功，访问路径：{}", url);
            return url;
            
        } catch (OSSException oe) {
            log.error("OSS异常：Error Message: {}, Error Code: {}, Request ID: {}, Host ID: {}", 
                    oe.getErrorMessage(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
            throw oe;
        } catch (ClientException ce) {
            log.error("客户端异常：{}", ce.getMessage());
            throw ce;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
